package org.pt.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.pt.components.Response;
import org.pt.dto.CreateWorkDto;
import org.pt.dto.UserFavoriteTag;
import org.pt.exception.*;
import org.pt.mapper.*;
import org.pt.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Slf4j
@Service
@RequiredArgsConstructor
public class WorkServiceImpl extends ServiceImpl<WorkMapper, Work> implements IService<Work> {

    private String parseModel = "hex";

    @Value("${torrent.storage.path}")
    private String TorrentStoragePath;
    @Value("${python.service.url}")
    private String pythonServiceUrl;
    @Value("${user.cover.default}")
    private String defaultCover;
    @Value("${user.cover.path}")
    private String CoverStoragePath;
    @Value("${work.tax.rate}")
    private float WorkTexRate;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private AnnounceLogsMapper announceLogsMapper;

    @Autowired
    private UserPossessMapper userPossessMapper;

    @Autowired
    private WorksTagsMapper worksTagsMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    public Response<List<String>> getWorkTags(int workId)
    {
        QueryWrapper<WorksTags> worksTagsQueryWrapper = new QueryWrapper<>();
        worksTagsQueryWrapper.eq("works_id", workId);
        List<WorksTags> worksTagsList = worksTagsMapper.selectList(worksTagsQueryWrapper);

        // 如果没有找到任何标签，返回空列表
        if (worksTagsList == null || worksTagsList.isEmpty()) {
            return Response.success(Collections.emptyList());
        }

        // 2. 提取所有tagId
        List<Integer> tagIds = worksTagsList.stream()
                .map(WorksTags::getTagId)
                .collect(Collectors.toList());

        // 3. 根据tagIds查询tags表中的内容
        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.in("id", tagIds);
        List<Tag> tags = tagMapper.selectList(tagQueryWrapper);

        // 4. 提取所有标签内容
        List<String> tagContents = tags.stream()
                .map(Tag::getContent)
                .collect(Collectors.toList());

        return Response.success(tagContents);
    }

    public boolean announce(String info_hash, String passkey, String event, String ip, int port, long uploaded, long downloaded) {

        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getPassKey, passkey);
        User user = userMapper.selectOne(userWrapper);

        LambdaQueryWrapper<Work> workWrapper = new LambdaQueryWrapper<>();
        workWrapper.eq(Work::getInfoHash, info_hash);
        Work work = workMapper.selectOne(workWrapper);

        if (work == null || user == null) {
            return false;
        }

        LambdaQueryWrapper<UserPossess> upWrapper = new LambdaQueryWrapper<>();
        upWrapper.eq(UserPossess::getUserId, user.getId());
        upWrapper.eq(UserPossess::getWorkId, work.getId());
        UserPossess userPossess = userPossessMapper.selectOne(upWrapper);
        if (userPossess == null) {
            return false;
        }
        UpdateWrapper<UserPossess> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userPossess.getId())
                .set("downloaded", downloaded)
                .set("uploaded", uploaded);
        userPossessMapper.update(updateWrapper);

        AnnounceLogs announceLogs = new AnnounceLogs();
        announceLogs.setWorkId(work.getId());
        announceLogs.setUserId(user.getId());
        announceLogs.setIp(ip);
        announceLogs.setPort(port);
        announceLogs.setUploaded(uploaded);
        announceLogs.setDownloaded(downloaded);
        announceLogs.setEvent(event);
        announceLogs.setTimestamp(new Date());

        announceLogsMapper.insert(announceLogs);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public Response<UserPossess> WorkPurchase(Integer userId, Integer workId) throws DBNotFoundExcepton, PurchaseException {

        User user = userMapper.selectById(userId);
        Work work = workMapper.selectById(workId);
        Integer createUserId = work.getUserId();
        if (user == null) {
            throw new DBNotFoundExcepton("user not found");
        } else if (work == null) {
            throw new DBNotFoundExcepton("work not found");
        }

        if (user.getId().equals(createUserId)){
            throw new PurchaseException("购买了自己的资源");
        }

        QueryWrapper<UserPossess> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserPossess::getUserId, userId)
                .eq(UserPossess::getWorkId, userId);
        UserPossess userPossess = userPossessMapper.selectOne(wrapper);

        if (userPossess != null) {
            throw new PurchaseException("重复购买");
        }


        int currentCost;
        if (work.isOnSale()) {
            currentCost = (int) (work.getCost() * work.getCostRate());
        } else {
            currentCost = work.getCost();
        }


        //TODO 根据魔力值判断用户是否有权利下载文件
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.setSql("magic_value = magic_value - " + currentCost)
                .eq(User::getId, userId)
                .ge(User::getMagicValue, currentCost);

        int updateCount = userMapper.update(null, updateWrapper);
        if (updateCount == 0) {
            throw new PurchaseException("扣减魔力值失败");
        }

        LambdaUpdateWrapper<User> creatorUserUpdateWrapper = new LambdaUpdateWrapper<>();
        creatorUserUpdateWrapper
                .setSql("magic_value = magic_value + " + currentCost*WorkTexRate)
                .eq(User::getId, createUserId);

        int creatorUpdateCount = userMapper.update(null, creatorUserUpdateWrapper);

        // 可选：校验是否成功
        if (creatorUpdateCount == 0) {
            throw new PurchaseException("获取资源收益失败");
        }


        //加入用户拥有列表
        userPossess = new UserPossess();
        userPossess.setUserId(userId);
        userPossess.setWorkId(workId);
        userPossessMapper.insert(userPossess);


        return Response.success(userPossess);
    }

    public List<UserPossess> getWorkListByUserId(Integer userId) {

        userPossessMapper.selectById(userId);

        QueryWrapper<UserPossess> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);  // 指定 userId 条件[2,5](@ref)
        List<UserPossess> resultList = userPossessMapper.selectList(wrapper);

        return resultList;
    }


    public ByteArrayResource getWorkTorrent(Integer userId, Integer workId) throws DBNotFoundExcepton, PurchaseException, TorrentReceiveException, IOException {
        User user = userMapper.selectById(userId);
        Work work = workMapper.selectById(workId);
        if (user == null) {
            throw new DBNotFoundExcepton("user not found");
        } else if (work == null) {
            throw new DBNotFoundExcepton("work not found");
        }

        QueryWrapper<UserPossess> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserPossess::getUserId, userId)
                .eq(UserPossess::getWorkId, workId);
        UserPossess userPossess = userPossessMapper.selectOne(wrapper);
        if (userPossess == null) {
            throw new PurchaseException("未购买资源");
        }

        String passkey = user.getPassKey();

        Path torrentDir = Paths.get(TorrentStoragePath);
        if (!Files.exists(torrentDir)) {
            Files.createDirectories(torrentDir); // 创建目录
        }
        Path torrentFilePath = torrentDir.resolve(work.getTorrent());
        if (!Files.exists(torrentDir)) {
            Files.createDirectories(torrentDir);
        }


        byte[] torrentBytes = Files.readAllBytes(torrentFilePath);
        ByteArrayResource torrentResource = new ByteArrayResource(torrentBytes) {
            @Override
            public String getFilename() {
                String filename = work.getName() + ".torrent";
                return URLEncoder.encode(filename, StandardCharsets.UTF_8);
            }
        };

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("torrent", torrentResource);
        body.add("passkey", passkey);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        ResponseEntity<byte[]> response = restTemplate.exchange(
                pythonServiceUrl + "/torrent/modify_torrent",
                HttpMethod.POST,
                new HttpEntity<>(body, headers),
                byte[].class
        );

        // 处理响应
        if (!response.getStatusCode().is2xxSuccessful()) {
            throw new TorrentReceiveException("torrent处理服务处理失败 ");
        }
        byte[] result = response.getBody();

        ByteArrayResource newTorrent = new ByteArrayResource(result) {
            @Override
            public String getFilename() {
                String filename = work.getName() + ".torrent";
                return URLEncoder.encode(filename, StandardCharsets.UTF_8);
            }
        };

        return newTorrent;
    }

    //错误回滚
    @Transactional(rollbackFor = Exception.class)
    public Response<Work> CreateTable(CreateWorkDto createWorkDto, Integer userId, MultipartFile cover, MultipartFile torrent) throws WorkException, IOException {

        String CoverPath = defaultCover;
        if (!cover.isEmpty()) {
            //TODO:处理传入的图片
            String originalFilename = cover.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); // 获取文件扩展名
            String timeStamp = String.valueOf(System.currentTimeMillis()); // 获取当前时间戳
            String newFilename = timeStamp + fileExtension; // 组合新文件名
            CoverPath = CoverStoragePath + newFilename;
        }
        byte[] fileBytes = cover.getBytes();
        // 写入文件
        Files.write(Paths.get(CoverPath), fileBytes);

        if (torrent.isEmpty()) {
            throw new TorrentReceiveException("Torrent is NULL");
        }

        //TODO:图片文件类型校验
//        if (!cover.getContentType().startsWith("image/")) {
//            return Response.fail("封面必须是图片格式（JPEG/PNG）");
//        }

        if (!torrent.getOriginalFilename().endsWith(".torrent")) {
            throw new TorrentReceiveException("file is not a torrent file");
        }
        //TODO:文件大小校验


        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();


        byte[] torrentBytes = torrent.getBytes();
        ByteArrayResource torrentResource = new ByteArrayResource(torrentBytes) {
            @Override
            public String getFilename() {
                return URLEncoder.encode(torrent.getOriginalFilename(), StandardCharsets.UTF_8);
            }
        };

        body.add("torrent", torrentResource);
        body.add("parse_model", parseModel);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);


        ResponseEntity<Map> response = restTemplate.exchange(
                pythonServiceUrl + "/torrent/parse_torrent",
                HttpMethod.POST,
                new HttpEntity<>(body, headers),
                Map.class
        );

        // 处理响应
        if (!response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> error = response.getBody();
            throw new TorrentReceiveException("torrent解析服务处理失败 " + error.get("error"));
        }
        Map<String, Object> result = response.getBody();


        Number lengthNumber = (Number) result.get("length");
        long length = lengthNumber.longValue();
//        String hashInfo = (String) result.get("hash_info");
        String infoHash = (String) result.get("info_hash");
        if (infoHash == null) {
            throw new TorrentReceiveException("返回的 info_hash 为空");
        }


        String torrentFilename = createWorkDto.getName() + "_" + System.currentTimeMillis();

        Work work = new Work();
        work.setUserId(userId);
        work.setName(createWorkDto.getName());
        work.setCover(CoverPath);
        work.setDescription(createWorkDto.getDesc());
        work.setCost(createWorkDto.getCost());
        work.setSize(length);
//        work.setHashInfo(hashInfo);
        work.setInfoHash(infoHash);
        work.setTorrent(torrentFilename);
        work.setDownload(0);
        int insertResult = workMapper.insert(work);

        //加入用户拥有列表
        UserPossess userPossess = new UserPossess();
        userPossess.setUserId(userId);
        userPossess.setWorkId(work.getId());
        userPossessMapper.insert(userPossess);

        try {
            int successCount = TagsUsage(work.getId(), createWorkDto.getTags());
        } catch (Exception e) {
            System.out.println("Tags插入失败" + e.getMessage());
        }


        //脱敏
        work.setTorrent("null");

        if (insertResult == 0)
            throw new WorkException("数据库保存失败");


//        保存文件
        Path torrentDir = Paths.get(TorrentStoragePath);
        if (!Files.exists(torrentDir)) {
            Files.createDirectories(torrentDir); // 创建目录
        }
        Path torrentFilePath = torrentDir.resolve(torrentFilename);
        if (!Files.exists(torrentDir)) {
            Files.createDirectories(torrentDir);
        }
        try (InputStream in = torrent.getInputStream()) {
            Files.copy(in, torrentFilePath, StandardCopyOption.REPLACE_EXISTING);
        }

        return Response.success(work);
    }

    public Response<List<Tag>> getTopTags(int limit) {

        if (limit > 20) limit = 20;

        List<Tag> Tags = tagMapper.selectList(
                new QueryWrapper<Tag>()
                        .orderByDesc("usage_count")
                        .last("LIMIT " + limit)
        );
        return Response.success(Tags);

    }


    private int TagsUsage(Integer workId, List<String> tags) {

        List<Tag> existTags = tagMapper.selectList(
                new QueryWrapper<Tag>().lambda()
                        .in(Tag::getContent, tags)
        );

        Set<String> existTagNames = existTags.stream()
                .map(Tag::getContent)
                .collect(Collectors.toSet());

        List<Tag> createList = new ArrayList<>();

        for (String tagName : tags) {
            if (existTagNames.contains(tagName)) {

                LambdaUpdateWrapper<Tag> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(Tag::getContent, tagName)
                        .setSql("usage_count = usage_count + 1");
                tagMapper.update(null, wrapper);


            } else {
                Tag newTag = new Tag();
                newTag.setContent(tagName);
                newTag.setUsageCount(1);
                createList.add(newTag);
            }
        }

        for (Tag existTag : existTags) {
            WorksTags worksTags = new WorksTags();
            worksTags.setWorkId(workId);
            worksTags.setTagId(existTag.getId());
            worksTagsMapper.insert(worksTags);
        }

        for (Tag createTag : createList) {

            tagMapper.insert(createTag);

            WorksTags worksTags = new WorksTags();
            worksTags.setWorkId(workId);
            worksTags.setTagId(createTag.getId());
            worksTagsMapper.insert(worksTags);

        }

        return createList.size() + existTags.size();

    }

    public Response<List<Work>> searchByTags(List<String> Tags) {

        Set<Integer> searchedTagIds = new HashSet<>();

        // 1. 模糊匹配 tag 内容，收集唯一 tag 的 id
        for (String tag : Tags) {
            QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("content", tag); // 模糊匹配 content 字段
            List<Tag> tagsFound = tagMapper.selectList(queryWrapper);
            for (Tag t : tagsFound) {
                searchedTagIds.add(t.getId()); // 加入唯一 tag id
            }
        }

        if (searchedTagIds.isEmpty()) {
            return Response.success(Collections.emptyList());
        }

        // 2. 根据 tag_id 查 works_tags 表，获取 work_id
        Set<Integer> workIds = new HashSet<>();
        for (Integer tagId : searchedTagIds) {
            QueryWrapper<WorksTags> wtQuery = new QueryWrapper<>();
            wtQuery.eq("tags_id", tagId);
            List<WorksTags> worksTagsList = worksTagsMapper.selectList(wtQuery);
            for (WorksTags wt : worksTagsList) {
                workIds.add(wt.getWorkId()); // 加入唯一 work id
            }
        }

        if (workIds.isEmpty()) {
            return Response.success(Collections.emptyList());
        }

        // 3. 根据 workIds 查询 works 表
        QueryWrapper<Work> workQuery = new QueryWrapper<>();
        workQuery.in("id", workIds);
        List<Work> searchedWorks = workMapper.selectList(workQuery);

        return Response.success(searchedWorks);
    }


    private String getFileExtension(String fileName) {
        if (fileName == null) {
            return "";
        }
        int lastDotIndex = fileName.lastIndexOf(".");
        if (lastDotIndex >= 0) {
            return fileName.substring(lastDotIndex);
        }
        return "";
    }


    public Response<List<Work>> getPossessWork(Integer id) {

        QueryWrapper<UserPossess> workQuery = new QueryWrapper<>();
        workQuery.in("user_id", id);
        List<UserPossess> UP = userPossessMapper.selectList(workQuery);

        List<Work> works = new ArrayList<>();

        Set<Integer> existingWorkIds = new HashSet<>();

        for (UserPossess up : UP) {
            Work work = workMapper.selectById(up.getWorkId());
            if (work != null && existingWorkIds.add(work.getId())) {
                works.add(work);
            }
        }

        QueryWrapper<Work> wtQuery = new QueryWrapper<>();
        wtQuery.eq("user_id", id);
        List<Work> workCreateByUser = workMapper.selectList(wtQuery);

        for (Work work : workCreateByUser) {
            if (work != null && existingWorkIds.add(work.getId())) {
                works.add(work);
            }
        }

        return Response.success(works);
    }

    public Response<List<Work>> getUserCreatedWork(Integer id) {
        QueryWrapper<Work> wtQuery = new QueryWrapper<>();
        wtQuery.eq("user_id", id);
        List<Work> workCreateByUser = workMapper.selectList(wtQuery);
        return Response.success(workCreateByUser);
    }

    public Response<List<Work>> getUserPurchasedWork(Integer id) {
        QueryWrapper<UserPossess> workQuery = new QueryWrapper<>();
        workQuery.in("user_id", id);
        List<UserPossess> UP = userPossessMapper.selectList(workQuery);

        List<Work> works = new ArrayList<>();

        for (UserPossess up : UP) {
            Work work = workMapper.selectById(up.getWorkId());
            if (work != null) {
                works.add(work);
            }
        }
        return Response.success(works);
    }

    public Response<List<Work>> searchByName(String name) {

        QueryWrapper<Work> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name); // 模糊匹配 content 字段
        List<Work> WorksFound = workMapper.selectList(queryWrapper);

        return Response.success(WorksFound);
    }

    public Response<String> setWorkCostByOwner(Integer userId, Integer workId, Integer newCost) throws DBNotFoundExcepton, WorkException {


        QueryWrapper<Work> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", workId)
                .eq("user_id", userId);


        Work work = workMapper.selectOne(queryWrapper);
        if (work == null) {
            throw new DBNotFoundExcepton("用户不是该资源所有者或资源不存在");
        }
        work.setCost(newCost);
        int success = workMapper.updateById(work);
        if (success == 0) {
            throw new WorkException("更新资源成本失败");
        }
        return Response.success("success");

    }

    public Response<String> userDeleteWork(Integer userId, Integer workId) throws DBNotFoundExcepton, WorkException {
        QueryWrapper<Work> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", workId)
                .eq("user_id", userId);

        Work work = workMapper.selectOne(queryWrapper);
        if (work == null) {
            throw new DBNotFoundExcepton("用户不是该资源所有者或资源不存在");
        }
        //删除记录
        int success = workMapper.deleteById(work.getId());

        //检查删除结果
        if (success == 0) {
            throw new WorkException("删除资源失败");
        }
        return Response.success("success");
    }

    public Response<List<UserFavoriteTag>> getFavoriteTags(Integer userId, Integer tagsNum) {

        List<Map<String, Object>> tagCounts = workMapper.findTopTagsByUserId(userId, tagsNum);

        if (tagCounts.isEmpty()) {
            return Response.success(Collections.emptyList());
        }

        List<Integer> tagIds = tagCounts.stream()
                .map(map -> ((Number) map.get("tags_id")).intValue())  // 确保类型正确
                .toList();

        List<Tag> tags = tagMapper.selectBatchIds(tagIds);

        // 将 Tag 列表转为 Map，便于通过 id 关联
        Map<Integer, Tag> tagMap = tags.stream()
                .collect(Collectors.toMap(Tag::getId, Function.identity()));

        List<UserFavoriteTag> favoriteTags = tagCounts.stream()
                .map(map -> {
                    Integer tagId = ((Number) map.get("tags_id")).intValue();
                    Integer usageCount = ((Number) map.get("count")).intValue();
                    Tag tag = tagMap.get(tagId);
                    return new UserFavoriteTag(tag, usageCount);
                })
                .toList();

        return Response.success(favoriteTags);
    }

    public Response<Page<Work>> getWorksPageByUser(String orderBy, int pageNum, int pageSize) throws Exception{
        // 创建分页对象
        Page<Work> page = new Page<>(pageNum, pageSize);

        // 根据orderBy参数设置排序规则
        if ("create_time".equalsIgnoreCase(orderBy)) {
            // 按创建时间排序（降序）
            page.addOrder(OrderItem.desc("create_time"));
        } else if ("download".equalsIgnoreCase(orderBy)) {
            // 按下载量排序（降序）
            page.addOrder(OrderItem.desc("download"));
        } else {
            // 默认按创建时间排序
            page.addOrder(OrderItem.desc("create_time"));
        }


        // 执行分页查询
        Page<Work> result = workMapper.selectPage(page, null);

        // 返回成功响应
        return Response.success(result);

    }

    public Response<Page<Work>> getWorksPageByUserWithTags(List<String> tags, String orderBy, int pageNum, int pageSize) {
        Page<Work> page = new Page<>(pageNum, pageSize);

        Set<Integer> workIds = null;
        if (tags != null && !tags.isEmpty()) {
            Set<Integer> searchedTagIds = new HashSet<>();

            // 模糊匹配 tag 内容，收集唯一 tag 的 id
            for (String tag : tags) {
                QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
                queryWrapper.like("content", tag);
                List<Tag> tagsFound = tagMapper.selectList(queryWrapper);
                for (Tag t : tagsFound) {
                    searchedTagIds.add(t.getId());
                }
            }

            if (!searchedTagIds.isEmpty()) {
                workIds = new HashSet<>();
                // 根据 tag_id 查 works_tags 表，获取 work_id
                QueryWrapper<WorksTags> wtQuery = new QueryWrapper<>();
                wtQuery.in("tags_id", searchedTagIds);
                List<WorksTags> worksTagsList = worksTagsMapper.selectList(wtQuery);
                for (WorksTags wt : worksTagsList) {
                    workIds.add(wt.getWorkId());
                }
            }
        }

        // 2. 构建作品查询条件
        QueryWrapper<Work> workQuery = new QueryWrapper<>();

        // 如果有符合条件的workIds，添加到查询条件
        if (workIds != null && !workIds.isEmpty()) {
            workQuery.in("id", workIds);
        }
        // 如果没有标签或未匹配到作品，且是标签搜索请求，返回空结果
        else if (tags != null && !tags.isEmpty()) {
            return Response.success(new Page<>(pageNum, pageSize, 0));
        }

        // 3. 添加排序条件
        if ("download".equalsIgnoreCase(orderBy)) {
            workQuery.orderByDesc("download");
        } else {
            workQuery.orderByDesc("create_time"); // 默认按创建时间排序
        }

        // 4. 执行分页查询
        Page<Work> result = workMapper.selectPage(page, workQuery);
        return Response.success(result);
    }
}
